/* Copyright (c) [2020] [ylc]. Licensed under Apache-2.0 License. */

#include "sht4x.h"
#include "i2cDriveM.h"

#define SHT_ADDR 	0x88			//7位ID为0x44，第8位为读写位

mI2CTypedef_t ShtI2c;				//io模拟i2c接口


//硬件接口

static void i2c_IoInit(void){
	//io初始化输出高，外部电路无上拉，内部则需要上拉

}

static void i2c_Delay(void){
	u16 i;
	for(i=0;i<10;i++){
		__NOP();
	}
}

static void i2c_SdaH(void){

}

static void i2c_SdaL(void){
	
}

static void i2c_SclH(void){
	
}

static void i2c_SclL(void){
	
}

static u8 i2c_ReadSda(void){
	return 0;
}

static u8 i2c_ReadScl(void){
	return 0;
}

//iic设备注册
void sht_i2c_init(mI2CTypedef_t *i2c)
{
	i2c->IIC_InitPort=i2c_IoInit;
	i2c->IIC_Delay=i2c_Delay;
	i2c->IIC_SDA_H=i2c_SdaH;
	i2c->IIC_SDA_L=i2c_SdaL;
	i2c->IIC_SCL_H=i2c_SclH;
	i2c->IIC_SCL_L=i2c_SclL;
	i2c->IIC_READ_SDA=i2c_ReadSda;
	i2c->IIC_READ_SCL=i2c_ReadScl;
}

//时序来自芯片手册
void sht_cmd_write(u8 cmd)
{
	i2c_Start(&ShtI2c);
	i2c_SendByte(&ShtI2c,SHT_ADDR|I2C_WR);
	i2c_WaitAck(&ShtI2c);
	i2c_SendByte(&ShtI2c,cmd);
	i2c_WaitAck(&ShtI2c);
	i2c_Stop(&ShtI2c);
}

//温度高 温度低 温度crc 湿度高 湿度低 湿度crc
//示例 65 08 1A 83 6B DE
u8 sht_ack_read(u8 *buf)
{
	u8 len=6;
	i2c_Start(&ShtI2c);
	i2c_SendByte(&ShtI2c,SHT_ADDR|I2C_RD);
	if(1==i2c_WaitAck(&ShtI2c)){	//ERROR
		goto ERR;
	}
	while(len-->1){
		*buf++ = i2c_ReadByte(&ShtI2c);
		i2c_Ack(&ShtI2c);
	}
	*buf++ = i2c_ReadByte(&ShtI2c);
	i2c_NAck(&ShtI2c);
	i2c_Stop(&ShtI2c);
	return 0;//正常返回
ERR:
	i2c_SdaErrorClear(&ShtI2c);
	return 1;	
}

u8 sht_crc8(const u8 *data1, u16 len) 
{
	const u8 POLYNOMIAL=0x31;
	u8 crc=0xFF;

	for (int j = len; j; --j) {
		crc ^= *data1++;

		for (int i = 8; i; --i) {
			crc = (crc & 0x80) ? (crc << 1) ^ POLYNOMIAL : (crc << 1);
		}
	}
	return crc;
}

//初始化
void sht_init(void)
{
	sht_i2c_init(&ShtI2c);
	ShtI2c.IIC_InitPort();
}


